﻿package com.utils
{
	/**
	 * 格式
	 * @author Kevin
	 */
	public class FormatTool 
	{
		/**
		 * 格式化数字格式
		 * @param	money
		 * @return
		 */
		static public function getDollarFormat(money:Number, hasSign:Boolean = true):String
		{
			var str:String = money.toString();
			var mode:int = str.length % 3;
			var head:String = str.substr(0, mode);
			
			if (str.length > 3 && str.length % 3 != 0)
			{
				head += ",";
			}
			str =  str.substr(mode);
			str = str.replace(/\d{3}/g, "$&,");
			if (hasSign)
			{
				str = "$" + head + str.substr(0, str.length - 1);
			}
			else
			{
				str = head + str.substr(0, str.length - 1);
			}
			return str;
		}
		
		static public function getDollarFormatValue(text:String):Number
		{
			text = text.replace(/\$|,|\s*/g, "");
			return Number(text);
		}
		
		/**
		 * 截取小数点
		 * @param	value			数值
		 * @param	decimalLength	截取小数位长度：默认保留两位小数
		 * @return
		 */
		static public function fixFormat(value:Number,decimalLength:int = 2):Number
		{			
			var divider:int = int(1 + "E" + decimalLength);
			value = Math.round(value * divider) / divider;
			return value;
		}
		
		/**
		 * 千   兆   十亿
		 */
		static public function getWorldMoneyFormat(money:Number, fractionDigits:uint = 0):String
		{
			var result:String = "";
			var flag:Boolean = false;
			var list:Array = [1E3, 1E6, 1E9];
			var label:Array = ["K", "M", "B"];
			for (var i:int = list.length - 1; i >= 0; i--)
			{
				if (money < list[i])
					continue;
				flag = true;
				break;
			}
			
			if (flag)
			{
				result = ((money / list[i]) as Number).toFixed(fractionDigits) + label[i];
			}
			else
			{
				result = money.toFixed(fractionDigits);
			}
			return result;
		}
		
		/**
		 * 时间格式显示
		 * @param	time
		 * @return
		 */
		static public function getTimerFormat(time:int):String
		{
			var result:String = "";
			var list:Array = [3600, 60, 1];
			
			time = Math.abs(Number(time));
			for (var i:int = 0; i < 3; i++)
			{
				var str:String = (i == 2) ? "":":";
				var num:int = time / list[i];
				if (num == 0 && i == 0)
					continue;
				time -= num * list[i];
				if (num < 10)
					result += "0" + num.toString() + str;
				else
					result += num.toString() + str;
			}
			return result;
		}
	}
}
